import React, { useState, useEffect } from 'react'
import {
  Modal,
  Card,
  Row,
  Col,
  Statistic,
  Progress,
  Typography,
  Space,
  Spin,
  Empty,
  Tag,
  List,
} from 'antd'
import {
  DatabaseOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  BarChartOutlined,
  CalendarOutlined,
} from '@ant-design/icons'
import {
  LineChart,
  Line,
  AreaChart,
  Area,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
} from 'recharts'
import type { Connection } from '@/types/connection'
import { formatDateTime, formatDuration, formatRelativeTime } from '@/utils'
import { getConnectionStats } from '@/services/connectionAPI'

const { Title, Text } = Typography

interface ConnectionStatsProps {
  visible: boolean
  connection: Connection | null
  onClose: () => void
}

interface ConnectionStatsData {
  total_executions: number
  success_rate: number
  avg_response_time: number
  last_used_at?: string
  most_used_databases: Array<{
    database: string
    count: number
  }>
  execution_trends: Array<{
    date: string
    count: number
    success_count: number
    avg_response_time: number
  }>
  recent_activities: Array<{
    id: string
    type: 'execution' | 'test' | 'schema_query'
    database?: string
    timestamp: string
    status: 'success' | 'failed'
    duration?: number
  }>
}

const ConnectionStats: React.FC<ConnectionStatsProps> = ({
  visible,
  connection,
  onClose,
}) => {
  const [loading, setLoading] = useState(false)
  const [statsData, setStatsData] = useState<ConnectionStatsData | null>(null)

  // 加载统计数据
  const loadStats = async () => {
    if (!connection) return

    setLoading(true)
    try {
      const response = await getConnectionStats(connection.id)
      if (response.success) {
        // 扩展API返回的数据，添加模拟的趋势和活动数据
        const extendedData: ConnectionStatsData = {
          ...response.data,
          execution_trends: generateMockTrends(),
          recent_activities: generateMockActivities(),
        }
        setStatsData(extendedData)
      }
    } catch (error) {
      console.error('Failed to load connection stats:', error)
      // 使用模拟数据
      setStatsData(generateMockStats())
    } finally {
      setLoading(false)
    }
  }

  // 生成模拟趋势数据
  const generateMockTrends = () => {
    const trends = []
    const now = new Date()
    
    for (let i = 6; i >= 0; i--) {
      const date = new Date(now)
      date.setDate(date.getDate() - i)
      
      const count = Math.floor(Math.random() * 50) + 10
      const success_count = Math.floor(count * (0.8 + Math.random() * 0.15))
      
      trends.push({
        date: date.toISOString().split('T')[0],
        count,
        success_count,
        avg_response_time: Math.floor(Math.random() * 200) + 100,
      })
    }
    
    return trends
  }

  // 生成模拟活动数据
  const generateMockActivities = () => {
    const activities = []
    const types: Array<'execution' | 'test' | 'schema_query'> = ['execution', 'test', 'schema_query']
    const databases = ['analytics', 'warehouse', 'logs', 'metrics']
    
    for (let i = 0; i < 10; i++) {
      const timestamp = new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000)
      activities.push({
        id: `activity-${i}`,
        type: types[Math.floor(Math.random() * types.length)],
        database: Math.random() > 0.3 ? databases[Math.floor(Math.random() * databases.length)] : undefined,
        timestamp: timestamp.toISOString(),
        status: Math.random() > 0.2 ? 'success' : 'failed' as 'success' | 'failed',
        duration: Math.floor(Math.random() * 5000) + 100,
      })
    }
    
    return activities.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())
  }

  // 生成模拟统计数据
  const generateMockStats = (): ConnectionStatsData => {
    return {
      total_executions: Math.floor(Math.random() * 1000) + 100,
      success_rate: Math.floor(Math.random() * 20) + 80, // 80-100%
      avg_response_time: Math.floor(Math.random() * 200) + 100, // 100-300ms
      last_used_at: new Date(Date.now() - Math.random() * 24 * 60 * 60 * 1000).toISOString(),
      most_used_databases: [
        { database: 'analytics', count: Math.floor(Math.random() * 100) + 50 },
        { database: 'warehouse', count: Math.floor(Math.random() * 80) + 30 },
        { database: 'logs', count: Math.floor(Math.random() * 60) + 20 },
        { database: 'metrics', count: Math.floor(Math.random() * 40) + 10 },
      ],
      execution_trends: generateMockTrends(),
      recent_activities: generateMockActivities(),
    }
  }

  useEffect(() => {
    if (visible && connection) {
      loadStats()
    }
  }, [visible, connection])

  // 获取活动类型显示信息
  const getActivityTypeInfo = (type: string) => {
    switch (type) {
      case 'execution':
        return { text: 'SQL执行', color: 'blue' }
      case 'test':
        return { text: '连接测试', color: 'green' }
      case 'schema_query':
        return { text: '结构查询', color: 'orange' }
      default:
        return { text: '未知', color: 'default' }
    }
  }

  // 图表颜色
  const COLORS = ['#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1']

  if (!connection) return null

  return (
    <Modal
      title={
        <Space>
          <BarChartOutlined />
          <span>连接统计 - {connection.name}</span>
        </Space>
      }
      open={visible}
      onCancel={onClose}
      footer={null}
      width={1000}
      style={{ top: 20 }}
    >
      {loading ? (
        <div style={{ textAlign: 'center', padding: '40px 0' }}>
          <Spin size="large" />
        </div>
      ) : !statsData ? (
        <Empty description="暂无统计数据" />
      ) : (
        <div>
          {/* 基础统计 */}
          <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
            <Col xs={24} sm={12} md={6}>
              <Card>
                <Statistic
                  title="总执行次数"
                  value={statsData.total_executions}
                  prefix={<DatabaseOutlined />}
                  valueStyle={{ color: '#1890ff' }}
                />
              </Card>
            </Col>
            
            <Col xs={24} sm={12} md={6}>
              <Card>
                <Statistic
                  title="成功率"
                  value={statsData.success_rate}
                  suffix="%"
                  prefix={<CheckCircleOutlined />}
                  valueStyle={{ color: '#52c41a' }}
                />
                <Progress
                  percent={statsData.success_rate}
                  size="small"
                  strokeColor="#52c41a"
                  showInfo={false}
                  style={{ marginTop: 8 }}
                />
              </Card>
            </Col>
            
            <Col xs={24} sm={12} md={6}>
              <Card>
                <Statistic
                  title="平均响应时间"
                  value={statsData.avg_response_time}
                  suffix="ms"
                  prefix={<ClockCircleOutlined />}
                  valueStyle={{ color: '#faad14' }}
                />
              </Card>
            </Col>
            
            <Col xs={24} sm={12} md={6}>
              <Card>
                <Statistic
                  title="最后使用"
                  value={statsData.last_used_at ? formatRelativeTime(statsData.last_used_at) : '从未使用'}
                  prefix={<CalendarOutlined />}
                  valueStyle={{ color: '#722ed1', fontSize: 16 }}
                />
                {statsData.last_used_at && (
                  <Text type="secondary" style={{ fontSize: 12 }}>
                    {formatDateTime(statsData.last_used_at)}
                  </Text>
                )}
              </Card>
            </Col>
          </Row>

          <Row gutter={[16, 16]}>
            {/* 执行趋势图 */}
            <Col xs={24} lg={16}>
              <Card title="执行趋势" size="small">
                <ResponsiveContainer width="100%" height={300}>
                  <LineChart data={statsData.execution_trends}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis 
                      dataKey="date" 
                      tick={{ fontSize: 12 }}
                      tickFormatter={(value) => new Date(value).toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' })}
                    />
                    <YAxis tick={{ fontSize: 12 }} />
                    <Tooltip
                      labelFormatter={(value) => formatDateTime(value)}
                      formatter={(value: any, name: string) => {
                        if (name === 'avg_response_time') {
                          return [`${value}ms`, '平均响应时间']
                        }
                        return [value, name === 'count' ? '总执行次数' : '成功次数']
                      }}
                    />
                    <Legend />
                    <Line
                      type="monotone"
                      dataKey="count"
                      stroke="#1890ff"
                      strokeWidth={2}
                      name="执行次数"
                    />
                    <Line
                      type="monotone"
                      dataKey="success_count"
                      stroke="#52c41a"
                      strokeWidth={2}
                      name="成功次数"
                    />
                  </LineChart>
                </ResponsiveContainer>
              </Card>
            </Col>

            {/* 数据库使用统计 */}
            <Col xs={24} lg={8}>
              <Card title="数据库使用统计" size="small">
                <ResponsiveContainer width="100%" height={300}>
                  <PieChart>
                    <Pie
                      data={statsData.most_used_databases}
                      cx="50%"
                      cy="50%"
                      labelLine={false}
                      label={({ database, percent }) => 
                        `${database} ${(percent * 100).toFixed(0)}%`
                      }
                      outerRadius={80}
                      fill="#8884d8"
                      dataKey="count"
                    >
                      {statsData.most_used_databases.map((entry, index) => (
                        <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                      ))}
                    </Pie>
                    <Tooltip />
                  </PieChart>
                </ResponsiveContainer>
              </Card>
            </Col>

            {/* 响应时间趋势 */}
            <Col xs={24}>
              <Card title="响应时间趋势" size="small">
                <ResponsiveContainer width="100%" height={200}>
                  <AreaChart data={statsData.execution_trends}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis 
                      dataKey="date" 
                      tick={{ fontSize: 12 }}
                      tickFormatter={(value) => new Date(value).toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' })}
                    />
                    <YAxis tick={{ fontSize: 12 }} />
                    <Tooltip
                      labelFormatter={(value) => formatDateTime(value)}
                      formatter={(value: any) => [`${value}ms`, '平均响应时间']}
                    />
                    <Area
                      type="monotone"
                      dataKey="avg_response_time"
                      stroke="#faad14"
                      fill="#faad14"
                      fillOpacity={0.3}
                    />
                  </AreaChart>
                </ResponsiveContainer>
              </Card>
            </Col>

            {/* 最近活动 */}
            <Col xs={24}>
              <Card title="最近活动" size="small">
                <List
                  dataSource={statsData.recent_activities}
                  renderItem={(activity) => {
                    const typeInfo = getActivityTypeInfo(activity.type)
                    return (
                      <List.Item>
                        <List.Item.Meta
                          title={
                            <Space>
                              <Tag color={typeInfo.color}>{typeInfo.text}</Tag>
                              {activity.database && (
                                <Text code>{activity.database}</Text>
                              )}
                              <Tag color={activity.status === 'success' ? 'success' : 'error'}>
                                {activity.status === 'success' ? '成功' : '失败'}
                              </Tag>
                            </Space>
                          }
                          description={
                            <Space>
                              <Text type="secondary">
                                {formatRelativeTime(activity.timestamp)}
                              </Text>
                              {activity.duration && (
                                <Text type="secondary">
                                  耗时: {formatDuration(activity.duration)}
                                </Text>
                              )}
                            </Space>
                          }
                        />
                      </List.Item>
                    )
                  }}
                  size="small"
                  pagination={{
                    size: 'small',
                    pageSize: 5,
                    showSizeChanger: false,
                  }}
                />
              </Card>
            </Col>
          </Row>
        </div>
      )}
    </Modal>
  )
}

export default ConnectionStats